<template>
  <div
    id="file_pdf"
    v-loading="isLoading"
    element-loading-text="加载中，请耐心等待..."
  ></div>
</template>
<script>
import jsPreviewPdf from "@js-preview/pdf";
import { base64ToURL, isBase64String } from "@/utils/file_preview_format";

export default {
  name: "FilePdf",
  props: {
    src: {
      required: true,
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  mounted() {
    if (this.src) {
      this.previewPdf();
    }
  },
  methods: {
    previewPdf() {
      this.isLoading = true;
      if (isBase64String(this.src)) {
        const blob = base64ToURL(this.src, "application/pdf");
        this.viewFile(blob);
      } else {
        this.viewFile(this.src);
      }
    },
    viewFile(src) {
      const myPdfPreviewer = jsPreviewPdf.init(
        document.getElementById("file_pdf"),
      );
      myPdfPreviewer
        .preview(src)
        .then(() => {
          this.$emit("succeed");
          this.isLoading = false;
        })
        .catch((e) => {
          this.$emit("error", e);
          this.isLoading = false;
        });
    },
  },
};
</script>
<style scoped lang="scss">
#file_pdf {
  width: 100%;
  height: 100%;
}
</style>